package cn.stronglink.esm27.collection.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * 服务端初始化，客户端与服务器端连接一旦创建，这个类中方法就会被回调，设置出站编码器和入站解码器
 **/

public class NettyServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final int protocolVersion;

    public NettyServerChannelInitializer(int protocolVersion) {
        this.protocolVersion = protocolVersion;
    }

    @Override
    protected void initChannel(SocketChannel channel) {
        // 使用netty自带的解码器返回值为byteBuf
        channel.pipeline().addLast(new NettyServerHandler(this.protocolVersion));
        // 字符串解码和编码
//        channel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//        channel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        // 心跳检测
        channel.pipeline().addLast(new IdleStateHandler(60, 60, 60, TimeUnit.SECONDS));
    }
}
